import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpHeaders,
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { LocalStorageService } from '../../local-storage/local-storage.service';
import { TOKEN } from '../../local-storage/local-storage.namespace';

const headers = new HttpHeaders({
  'Content-Type': 'application/json',
});

/**
 * 前置请求拦截器
 */
@Injectable()
export class PreInterceptor implements HttpInterceptor {
  constructor(private localStorageService: LocalStorageService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    if (req.url.indexOf('/assets') === 0) {
      return next.handle(req);
    }

    const apiReq = req.clone({
      url: `/api/${req.url}`,
      headers: headers.set(
        'Authorization',
        `Bearer ${this.localStorageService.get(TOKEN)}`,
      ),
    });
    return next.handle(apiReq);
  }
}
